//
//  TESegmentedControl.m
//  SmartRoadShow
//
//  Created by Tracy E on 10-9-19.
//  Copyright 2010 simonwang142232@gmail.com. All rights reserved.
//

#import "TESegmentedControl.h"
#import <QuartzCore/QuartzCore.h>

#define selectedImage [UIImage imageNamed:@"selected.png"]
#define unselectedImage [UIImage imageNamed:@"unselected.png"]

@implementation TESegmentedControl

@synthesize delegate;

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        [self setFrame:frame];
		self.layer.cornerRadius = 5;
		self.layer.masksToBounds =	YES;

		
		segments = [[NSMutableArray alloc] initWithCapacity:3];
    }
    return self;
}

- (void)setItems:(NSArray *)items{
    
	for (int i = 0; i < [items count]; i++) {
		UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
		[button setTag:i];
		[button setFrame:CGRectMake((self.frame.size.width / [items count]) * i, 0, self.frame.size.width / [items count], self.frame.size.height)];
		[button setBackgroundImage:unselectedImage forState:UIControlStateNormal];
		[button setBackgroundImage:unselectedImage forState:UIControlStateHighlighted];
		[button setTitle:[items objectAtIndex:i] forState:UIControlStateNormal];
		[button.titleLabel setFont:[UIFont boldSystemFontOfSize:13.5]];
		[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
		[button addTarget:self action:@selector(segmentChangedToIndex:) forControlEvents:UIControlEventTouchDown];
		[self addSubview:button];
		[segments addObject:button];
	}
}

- (void)setSelectedSegmentIndex:(NSInteger)index{
    
	for (int i = 0; i < [segments count]; i++) {
		if (i == index) {
			[[segments objectAtIndex:i] setBackgroundImage:selectedImage forState:UIControlStateNormal];
			[[segments objectAtIndex:i] setBackgroundImage:selectedImage forState:UIControlStateHighlighted];
		}
		else {
			[[segments objectAtIndex:i] setBackgroundImage:unselectedImage forState:UIControlStateNormal];
			[[segments objectAtIndex:i] setBackgroundImage:unselectedImage forState:UIControlStateHighlighted];
		}
	}
}

- (void)segmentChangedToIndex:(UIButton *)sender{
	[self setSelectedSegmentIndex:sender.tag];
	[delegate segmentedControl:self segmentDidChangeToIndex:sender.tag];
}


- (void)dealloc {
    [super dealloc];
}


@end
